import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
import Link from 'next/link'

import Headback from '../../components/Headback'

import styles from '../../styles/Dingdan.module.scss'
import { useEffect, useState } from 'react'
import { List, Radio, Image, Toast, Button, Space, Tag, Rate, Input, Divider } from 'antd-mobile'
import { DingdanStat, Gender } from '../../models/enums'
import { options } from '../../assets/college/data'
import { DingdanService, RemarkService, UserService } from '../../services'
import { IDingdan, IUser } from '../../models/types'
import { Warnicon, Winicon } from '../../components/Icon'
import router from 'next/router'

interface Props {
  dingdan: IDingdan
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const token = ctx.req.cookies?.token
  const dingdanId = ctx.query.dingdanid as string
  const cart = ctx.query.cart as string

  const res = await DingdanService.datail(dingdanId, cart, token)

  if (res.stat === 'OK') {
    return {
      props: {
        dingdan: res.data
      }
    }
  }
  return {
    redirect: {
      destination: '/default',
      permanent: false
    }
  }
}

const Dingdan: NextPage<Props> = ({ dingdan }) => {

  const { _id, name, address, note, book, cart } = dingdan
  const serial = _id // 等个十六进制转
  const info = ['订单编号', '收件人', '联系方式', '收获地址', '备注']
  const infoKey = [serial, name, dingdan.phone, address, note]

  const [dingdanState, setDingdanState] = useState(cart.confirm)
  const [rate, setRate] = useState(1)
  const [remark, setRemark] = useState('')


  async function clipboard(value: string) {
    try {
      await navigator.clipboard.writeText(value)
      Toast.show({ content: <Winicon text='复制成功' /> })
    } catch (error) { }
  }
  async function judge(flag: boolean) {
    if (!confirm(flag ? '确认收货' : '确认取消订单')) return
    const cartId = router.query.cart as string
    const res = await DingdanService.confirm(cartId, flag)
    if (res.stat === 'OK') {
      Toast.show({ content: <Winicon text='操作成功' /> })
      setDingdanState(flag ? DingdanStat.Queren : DingdanStat.Cancel)
      router.back()
    } else {
      Toast.show(res.msg);
    }
  }

  async function addRemark() {
    const str = remark.replace(/\s*/g, "")
    if (str.length < 5) Toast.show({ content: <Warnicon text='需要大于5个字' /> })
    else if (rate < 1) Toast.show({ content: <Warnicon text='至少一星' /> })
    else {
      const res = await RemarkService.add(book._id, remark, rate, _id)
      if (res.stat === 'OK') {
        Toast.show({ content: <Winicon text={'发布成功'} /> })
        router.push(`/goods/${book._id}`)
      }
      else Toast.show({ content: <Warnicon text={res.msg} /> })
    }
  }
  return (
    <div className='page'>
      <Head>
        <title>订单页</title>
      </Head>
      <Headback page='订单页' />
      <div className={styles.wrap}>
        <main className={styles.book}>
          <List header={
            <Space>
              {dingdanState === DingdanStat.Cancel &&
                <Tag color='default'>已取消订单</Tag>}
              {dingdanState === DingdanStat.Queren &&
                <Tag color='success'>确认收货</Tag>}
              {dingdanState === DingdanStat.Waiting &&
                <Tag color='warning'>货物运输中</Tag>}
              {dingdanState === DingdanStat.Daohuo &&
                <Tag color='success'>货物送达</Tag>}
              {dingdanState === DingdanStat.Empty &&
                <Tag color='danger'>缺货/断货</Tag>}
            </Space>
          }>

            <List.Item
              arrow={false}
              key={book._id}
              onClick={() => router.push(`/goods/${book._id}`)}
              prefix={
                <div className={styles.img}>
                  <Image alt='' src={book.banner[0]} fit='cover'
                    width={45} height={60} />
                </div>
              }
              extra={cart.prices.reduce((a, b) => {
                return a + b
              }, 0) + ' 元'}
              description={
                <Space>
                  {
                    cart.names.map((item, idx) =>
                      <Tag key={idx} color='default'>{item}</Tag>)
                  }
                </Space>
              }
            >{book.title}
            </List.Item>

          </List>
          <div className={styles.allprice}>
            <p>本单支付:</p>
            <span>¥{cart.prices.reduce((a, b) => {
              return a + b
            }, 0)}</span>
          </div>
        </main>
        <div className={styles.info}>
          {info.map((item, idx) => (
            <div key={idx} className={styles.item}>
              <aside>
                <span>{item}</span>
              </aside>
              <main>{infoKey[idx]}</main>
              {idx === 0 && <li
                onClick={() => clipboard(_id)}
              >复制</li>}
            </div>
          ))}
        </div>
        {
          dingdanState === DingdanStat.Queren && <div className={styles.remark}>
            <h3>评价</h3>
            <Rate
              value={rate}
              style={{ '--active-color': '#00b578' }}
              onChange={val => setRate(val)} />
            <Divider />
            <div className={styles.input}>
              <Input
                value={remark}
                placeholder={'写出你对货物的评价~'}
                onChange={v => setRemark(v)}
                maxLength={50}
                onEnterPress={async () => await addRemark()}
              />
              <button onClick={async () => await addRemark()}>发送</button>
            </div>

          </div>

        }
      </div>
      <div className={styles.btn}>
        <Button
          disabled={dingdanState !== DingdanStat.Daohuo}
          color='success' shape='rounded' size='small'
          onClick={async () => { await judge(true) }}
        >确认收货</Button>
        <Button
          disabled={dingdanState !== DingdanStat.Waiting}
          color='primary' shape='rounded' size='small'
          onClick={async () => { await judge(false) }}
        >取消订单</Button>
        <Button fill='outline' shape='rounded' size='small'
          onClick={() => { }}
        >联系卖家</Button>
      </div>
    </div>
  )
}

export default Dingdan
